<?php

declare(strict_types=1);

namespace App\Model;

use Hyperf\DbConnection\Model\Model;

/**
 *  送礼物记录
 */
class GiftBatchLog extends Model
{
    protected $table = 'gift_batch_log';

    protected $fillable = [
        "user_id", "receive_user_id", "flag", "gift_id", "gift_type", "send_user_id"
    ];

    /**
     * 礼物记录
     */
    static function addRecord(
        $userId = 0,
        $receiveUserId = [],
        $giftId = 1,
        $giftType = Gift::TYPE_SYS,
        $sendUserId = []
    ) {
        if (!$userId || (empty($receiveUserId) && empty($sendUserId))) return false;
        if (!is_array($receiveUserId)) $receiveUserId = [$receiveUserId];
        $info = [
            'user_id' => $userId,
            'receive_user_id' => empty($receiveUserId) ? '' : json_encode($receiveUserId),
            'send_user_id' => empty($sendUserId) ? '' : json_encode($sendUserId),
            'gift_id' => $giftId,
            'gift_type' => $giftType,
            'flag' => 1,
        ];
        return self::create($info);
    }

    /**
     * 已经赠送礼物的
     */
    static function sendSysGiftLogs($userId = 0, $type = 'today', $data = 'list')
    {
        $where = [
            ['user_id', $userId],
            ['gift_type', Gift::TYPE_SYS],
            ['flag', 1]
        ];
        switch ($type) {
            case 'today':
                $where[] = ['created_at', '>', date('Y-m-d')];
                $where[] = ['created_at', '<', date('Y-m-d', strtotime('+1 day'))];
                break;
            case 'late':
                //查找近10天的
                $where[] = ['created_at', '>', date('Y-m-d', strtotime('-10 day'))];
            default:
                break;
        }
        return $data == 'list' ? self::where($where)->get()->toArray() : self::where($where)->count();
    }

    /**
     * 周期内赠送系统礼物
     */
    static function checkSendCount($userId = 0, $offTime = 0)
    {
        $where = [
            ['user_id', $userId],
            ['gift_type', Gift::TYPE_SYS],
            ['flag', 1]
        ];
        $offTime && $where[] = ['created_at', '>', date('Y-m-d H:i:s', time() - $offTime)];
        return self::where($where)->count();
    }
}
